<!--
 * @Author: DT1604\ZPL zhoupeili@dpc.com.cn
 * @Date: 2022-05-28 09:48:37
 * @LastEditors: DT1604\ZPL zhoupeili@dpc.com.cn
 * @LastEditTime: 2022-06-23 17:20:31
 * @FilePath: \energy-om-platform\src\views\cabint\log.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="cmds">
    <el-form
      :model="form"
      :rules="rules"
      ref="form" size="small"
      label-width="120px"
      v-loading="uploading"
      element-loading-text="文件上传中"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.3)"
    >
      <el-form-item label="设备类型" prop="equipTypeCode">
        <el-select clearable
          v-model="form.equipTypeCode"
          placeholder="请选择设备类型"
          @change="equipChange"
        >
          <el-option
            v-for="item in equipTypeList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="固件类型" prop="partType">
        <el-select clearable
          v-model="form.partType"
          :disabled="!form.equipTypeCode"
          placeholder="请选择固件类型"
        >
          <el-option
            v-for="item in componentList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <div class="tips">
        <el-link type="danger" :underline="false"
          >注：软件版本格式为：数字_数字_数字_数字_数字 <br />示例：1_0_0_0_0
        </el-link>
      </div>
      <el-form-item label="软件版本" prop="version">
        <el-input clearable
          v-model="form.version"
          onkeyup="value=value.replace(/[^\x00-\xff]/g, '')"
          placeholder="请输入软件版本"
        ></el-input>
      </el-form-item>
      <el-form-item label="MD5校验码" prop="md5">
        <el-input v-model="form.md5" placeholder="请输入MD5校验码" clearable></el-input>
      </el-form-item>
      <el-form-item label="下载方式" prop="dowloadType">
        <el-select v-model="form.dowloadType" placeholder="请选择下载方式" clearable>
          <el-option
            :disabled="item.code !== 0"
            v-for="item in enums.DOWNLOAD_TYPE"
            :key="item.code"
            :label="item.label"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-select v-model="form.isEnable" placeholder="请选择是否启用" clearable>
          <el-option
            v-for="item in enums.YES_OR_NO"
            :key="item.code"
            :label="item.label"
            :value="item.code"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <div class="tips">
        <el-link type="danger" :underline="false"
          >注：若填写此项，则会根据所填内容创建目录；否则默认根目录
          <br />可以用'/' 不能用'\',如：www/datas
        </el-link>
      </div>
      <el-form-item label="目录">
        <el-input clearable
          v-model="ftpath"
          placeholder="请输入目录"
          @keyup.native="keyUp"
          @keydown.native="keydown"
          :disabled="fileList.length > 0"
        ></el-input>
      </el-form-item>
      <el-form-item label="上传文件" prop="fileName">
        <el-upload
          class="upload-demo"
          drag
          action="#"
          multiple
          :limit="1"
          :http-request="uploadRequest"
          :on-change="handleChange"
          :on-exceed="esceedUpload"
          :on-remove="removeFile"
          :file-list="fileList"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </el-form-item>
      <el-form-item label="版本说明" prop="remark">
        <el-input
          type="textarea"
          rows="4"
          v-model="form.remark"
          placeholder="请输入版本说明"
        >
        </el-input>
      </el-form-item>

      <el-form-item class="nobottom">
        <el-checkbox size="medium" v-model="form.isAutoUpgrade"
          >开启自动升级</el-checkbox
        >
      </el-form-item>
      <el-form-item class="dialog-footer nobottom">
        <el-button @click="resetForm('form')" size="small">取消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="submitForm('form')"
          :loading="btnLoading"
          >确定</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

import {  partType, softwareVersions } from "@/api/file";
import { handleConfirm } from "@/utils/messageBox";

export default {
  props: {
    updateDialogVisible: {
      default: true,
      type: Boolean,
    },
    // 设备类型
    equipType: {
      type: String,
      default: "",
    },
    equipTypeList: {
      type: Array,
      default: [],
    },
    currentRow: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      form: {
        equipTypeCode: "", //类型
        partType: "",
        version: "", //版本号
        md5: "", //MD5校验码
        filePath: "",
        fileName: "",
        remark: "",
        isAutoUpgrade: "",
        dowloadType: 0,
        isEnable: 1,
      },
      ftpath: "", //文件目录
      rules: {
        equipTypeCode: [
          { required: true, message: "请选择设备类型", trigger: "change" },
        ],
        fileName: [
          { required: true, message: "请上传文件", trigger: "change" },
        ],
        partType: [
          { required: true, message: "请选择固件类型", trigger: "change" },
        ],
        version: [
          { required: true, message: "请输入软件版本", trigger: "blur" },
        ],
        dowloadType: [
          { required: true, message: "请选择下载方式", trigger: "change" },
        ],
        isEnable: [
          { required: true, message: "请选择是否启用", trigger: "change" },
        ],
        md5: [{ required: true, message: "请输入md5", trigger: "blur" }],
        remark: [
          { required: true, message: "请输入版本说明", trigger: "blur" },
        ],
      },
      btnLoading: false, //按钮loading
      formData: null, //上传模板数据
      fileList: [], //文件列表

      componentList: [],
      uploading: false,
    };
  },

  computed: {
    ...mapGetters(["enums", "equipTypeCode"]),
  },

  watch: {
    updateDialogVisible: {
      handler(newVal, oldVal) {
        if (!newVal) {
          this.resetData();
        }
      },
      immediate: true,
    },
    currentRow: {
      handler(newVal, oldVal) {
        if (newVal.id) {
          //编辑
          let {
            equipTypeCode,
            partType,
            version,
            md5,
            filePath,
            fileName,
            remark,
            isAutoUpgrade,
            dowloadType,
            isEnable,
          } = {
            ...newVal,
          };
          this.form = {
            equipTypeCode,
            partType,
            version,
            md5,
            filePath,
            fileName,
            remark,
            isAutoUpgrade,
            dowloadType,
            isEnable,
          };

          this.fileList = [{ url: filePath, name: fileName }];
          this.ftpath = filePath;
          this.partList(equipTypeCode);
        } else {
          this.clearForm();
        }
      },
      immediate: true,
    },
  },

  methods: {
    async partList(e) {
      this.componentList = [];
      let datas = await partType("/list", "get", {
        equipTypeCode: e,
      });
      this.componentList = datas.data;
    },
    //限制输入特殊字符
    keyUp(e) {
      e.target.value = e.target.value.replace(
        /[`~!@#$%^&*()_\-+=<>?:"{}|,.\;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g,
        ""
      );
      this.ftpath = e.target.value;
    },
    // 只能输入汉字、英文、数字
    keydown(e) {
      e.target.value = e.target.value.replace(
        /[^\a-\z\A-\Z0-9\u4E00-\u9FA5/]/g,
        ""
      );
      this.ftpath = e.target.value;
    },
    esceedUpload(file) {
      this.$message.warning("只能上传一个文件!");
    },
    uploadRequest(file) {
      //自定义上传
      this.formData = new FormData();
      this.formData.append("file", file.file);
      this.formData.append("path", this.ftpath ? this.ftpath : "");

      this.uploading = true;
      softwareVersions("/upload", "post", this.formData, 1)
        .then((res) => {
          if (res.code == 200) {
            let datas = res.data;
            this.form.fileName = datas.fileName;
            this.form.filePath = datas.filePath;
          } else {
            this.fileList = [];
          }
        })
        .finally(() => {
          this.uploading = false;
        })
        .catch(() => {
          this.fileList = [];
        });
    },
    async equipChange(e) {
      this.componentList = [];
      this.form.partType = "";
      let datas = await partType("/list", "get", { equipTypeCode: e });
      this.componentList = datas.data;
    },
    clearForm() {
      this.form = {
        equipTypeCode: "", //类型
        partType: "",
        version: "", //版本号
        md5: "", //MD5校验码
        filePath: "",
        fileName: "",
        remark: "",
        isAutoUpgrade: "",
        dowloadType: 0,
        isEnable: 1,
      };
      this.ftpath = "";
      this.fileList = [];
    },
    resetData() {
      this.resetForm("form");
      this.clearForm();
      this.btnLoading = false;
      this.emitClose();
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.isDoAdd();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.emitClose();
    },
    // 通知关闭弹框
    emitClose() {
      this.clearForm();
      this.$emit("cancelDialog");
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3);
    },
    removeFile(file, fileList) {
      this.fileList = [];
    },

    async doAdd() {
      this.btnLoading = true;
      let param = { ...this.form };
      param.isAutoUpgrade = param.isAutoUpgrade ? 1 : 0;
      let url = this.currentRow.id
        ? `/update/${this.currentRow.id}`
        : "/insert";
      await softwareVersions(url, "post", param, 1)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success(res.message);
            this.emitClose();
            this.$emit("updateData");
          }
        })
        .finally((complete) => {
          this.btnLoading = false;
        });
    },
    isDoAdd() {
      let msg = this.currentRow.id ? "编辑" : "新增";
      let tips = "保存文件后将自动开启自动升级任务，请确认！！！";
      handleConfirm(
        this.form.isAutoUpgrade ? tips : `确定要${msg}升级文件管理吗？`,
        "提示"
      )
        .then((res) => {
          this.doAdd();
        })
        .catch((err) => {});
    },
  },
};
</script>

<style scoped lang="scss">
.dialog-footer {
  text-align: right;
}
.tips {
  margin: 0 15% 5px;
}
.cmds {
  .el-select {
    width: 100%;
  }
}
.nobottom {
  margin: 0;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #333;
}
</style>
